﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EPiServer.Data.Dynamic;
using System.ComponentModel.DataAnnotations;
using EPiServer.Personalization.VisitorGroups;
using EPiServer.Data;

namespace CriteriaPack.DownloadCriterion
{


    namespace EPiServer.Personalization
    {
        public class DownloadModel : CriterionModelBase
        {
            [Required, DojoWidget]
            public string VirtualPath { get; set; }

            #region IDynamicData Members

            public Identity Id
            {
                get;
                set;
            }

            #endregion

            public override ICriterionModel Copy()
            {
                return base.ShallowCopy();
            }
        }

        [VisitorGroupCriterion(DisplayName = "Downloaded file", Category = "URL Criteria")]
        public class DownloadCriterion : CriterionBase<DownloadModel>
        {
            public override bool IsMatch(System.Security.Principal.IPrincipal principal, HttpContextBase httpContext)
            {
                if (httpContext.Request.Cookies["EPi:DownloadedFile"] != null) return (bool)httpContext.Request.Cookies["EPi:DownloadedFile"].Value.Contains(Model.VirtualPath);
                return false;
            }

            public override void Subscribe(ICriterionEvents criterionEvents)
            {
                criterionEvents.StartRequest += new EventHandler<CriterionEventArgs>(criterionEvents_StartRequest);
            }

            void criterionEvents_StartRequest(object sender, CriterionEventArgs e)
            {
                if (e.HttpContext.Request.Url.ToString().ToLower().Contains(Model.VirtualPath.ToLower()))
                {
                    var hc = e.HttpContext.Request.Cookies["EPi:DownloadedFile"];
                    if (hc == null) hc = new HttpCookie("EPi:DownloadedFile");
                    hc.Expires = DateTime.Now.AddMonths(1);
                    hc.Value += Model.VirtualPath + ";";
                    e.HttpContext.Response.AppendCookie(hc);
                }
            }

            public override void Unsubscribe(ICriterionEvents criterionEvents)
            {
                criterionEvents.StartRequest -= new EventHandler<CriterionEventArgs>(criterionEvents_StartRequest);
            }
        }
    }

}
